"""
@Author : 合肥一元数智教育科技有限公司
@Date :  2025/7/18 10:51
@Description :   用户自定义工具类

"""
import datetime
import hashlib
import json

from django.http import HttpResponse

from django_vue_back_2512 import settings
import jwt

from qiniu import Auth
from qiniu import BucketManager
from django_vue_back_2512.settings import QN_SECRET_KEY,QN_ACCESS_KEY ,BUCKET_NAME

#  自定义序列化
def customer_serializable(obj):
    if isinstance(obj, datetime.datetime):
        return obj.strftime('%Y-%m-%d')

    raise TypeError(f'Type {type(obj)} not serializable')

class CustomerUtil:

    @staticmethod
    def get_request_params(request):
        param_dict = json.loads(request.body.decode('utf8'))
        return param_dict

    @staticmethod
    def create_token(payload):
        return jwt.encode(payload, settings.SECRET_KEY, algorithm='HS256')

    @staticmethod
    def decode_token(token):
        return jwt.decode(token, settings.SECRET_KEY, algorithms=['HS256'])

    @staticmethod
    def md5(info):
        return hashlib.md5(info.encode('utf-8')).hexdigest()

    @staticmethod
    def response_json(data):
        result = json.dumps(data, default=customer_serializable)
        return HttpResponse(result, content_type='application/json; charset=UTF-8')

    @staticmethod
    def create_qiniu_token():
        # 构建鉴权对象
        q = Auth(QN_ACCESS_KEY, QN_SECRET_KEY)
        # 要上传的空间
        bucket_name = 'django2512'
        # 上传后保存的文件名
        key = datetime.datetime.utcnow().strftime('%Y%m%d%H%M%S')
        # 生成上传 Token，可以指定过期时间等
        # 上传策略示例
        # https://developer.qiniu.com/kodo/manual/1206/put-policy
        policy = {}
        # 3600为token过期时间，秒为单位。3600等于一小时
        token = q.upload_token(bucket_name, None, 3600, policy)

        return key, token

    @staticmethod
    def remove_source(key):
        # 初始化Auth状态
        q = Auth(QN_ACCESS_KEY, QN_SECRET_KEY)
        # 初始化BucketManager
        bucket = BucketManager(q)
        # 你要测试的空间， 并且这个key在你空间中存在
        bucket_name = BUCKET_NAME
        # 删除bucket_name 中的文件 key
        bucket.delete(bucket_name, key)
